import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 管理客户端连接实例
 * @author tzj
 *
 * 2016-11-25  下午3:11:38
 */
public class ConnAdminTestHandle extends ChannelInboundHandlerAdapter{

	private  int  LOGIN=0x87654321;
	
	private  int  DATAUPLOAD=0X55AA0100;
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		
		ByteBuf buf=ctx.alloc().buffer();
		
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("username", "admin");
		map.put("password", "admin");
		String jsonString=JSON.toJSONString(map);
		
		buf.writeInt(0x87654321);
		buf.writeBytes(jsonString.getBytes("utf-8"));
		
		ctx.writeAndFlush(buf);//登录
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		
		ByteBuf buf = (ByteBuf) msg;
		
		byte[] bs=null;
		if(buf.readInt()==LOGIN){
			bs=new byte[buf.readableBytes()];
			buf.readBytes(bs);
			
			String jsonstring=new String(bs,"utf-8");
	
			System.out.println(jsonstring);
		}else
		{
			
			buf.resetReaderIndex();
			bs=new byte[buf.readableBytes()];
			buf.readBytes(bs); //如果是上传的数据放在bs里面自行解析处理
			
			
			
		}
		

		
		super.channelRead(ctx, msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		super.exceptionCaught(ctx, cause);
	}

	
}
